package com.cabrida.livestar.util;

import java.util.Map;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.cabrida.livestar.pay.PayResult;


/**
 * 支付宝支付
 */
public class AliPayManager {
	public static final String TAG ="AliPayManager";
	private Activity mActivity;
	private Handler returnResultHandler;
	
	/** 支付宝支付业务：入参app_id */
	public static final String APPID = "2017031306193497";
	
	/** 支付宝账户登录授权业务：入参pid值 */
	public static final String PID = "2088521453768573";
	/** 支付宝账户登录授权业务：入参target_id值 */
	public static final String TARGET_ID = "";

	/** 商户私钥，pkcs8格式 */
	/** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
	/** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
	/** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
	/** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
	/** 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */
	public static final String RSA2_PRIVATE = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnoSOAJjHuZH5eL1J4JvVnBFBB3URzlneNFxfdavWjj1oEDWO2Ih+r9Oo6d4gAwJSWwxac80GDY9mNs48+aUOAEMjr1d3Q8XN6ftzG+VoH/PjhC6Hkxg+XCSVpTaXcfRmp08HeeqaZw4HExAHzYk6vJzZ39HKLjjzAaduvHPGbajQEKImIXGIjw/bvl3MJXs373o2wIC1vdzZ2G9yOTRzxWSffT4wSvXoAEpY7MCGa5yPlOdZNCBTkfNWfzYGpGtRn3cGc9Hgx8awHADzHI2fL4YWIyah1MT7luhf17yFB7I9zcJFDfvg6/UToFOz51/IZcVmdBMWfsoWYCHx3d4SMwIDAQAB";
	public static final String RSA_PRIVATE = "";
	
	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_CHECK_FLAG = 2;
	
	public AliPayManager(Activity activity,Handler handler) {
		mActivity = activity;
		returnResultHandler = handler;
	}
	
	public void aliPay(final String orderInfo){
		
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				PayTask alipay = new PayTask((Activity)mActivity);
				Map<String, String> result = alipay.payV2(orderInfo, true);
				L.e(TAG, "aliPay", result.toString());
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}
	
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			// DialogUtil.dismissDialog();

			switch (msg.what) {
			case SDK_PAY_FLAG: {
				@SuppressWarnings("unchecked")
				PayResult payResult = new PayResult((Map<String, String>) msg.obj);

				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();

				String resultStatus = payResult.getResultStatus();

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(mActivity, "支付成功", Toast.LENGTH_SHORT)
							.show();

					/**
					 * 返回给调用PayManager的类，what为1
					 */
					Message msgReturn = new Message();
					msgReturn.what = 1;
					msgReturn.obj = "支付成功";
					returnResultHandler.sendMessage(msgReturn);
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(mActivity, "支付结果确认中", Toast.LENGTH_SHORT)
								.show();
						/**
						 * 返回给调用PayManager的类，what为2
						 */
						Message msgReturn = new Message();
						msgReturn.what = 2;
						msgReturn.obj = "支付结果确认中";
						returnResultHandler.sendMessage(msgReturn);

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT)
								.show();
						/**
						 * 返回给调用PayManager的类，what为-1
						 */
						Message msgReturn = new Message();
						msgReturn.what = -1;
						msgReturn.obj = "支付失败";
						returnResultHandler.sendMessage(msgReturn);

					}

				}

				//submit(payResult);

				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(mActivity, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};
}
